import { Request, Response } from 'express';
import { TodoList } from '../model/models';

export const createTodoList = async (req: Request, res: Response) => {
  try {
    const { title, desc } = req.body;
    const todoList = await TodoList.create({ title, desc });
    res.status(201).json(todoList.toJSON());
  } catch (error) {
    console.error('Error creating todoList:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

export const getTodoList = async (req: Request, res: Response) => {
  try {
    const todoLists = await TodoList.findAll();
    res.json(todoLists.map(todoList => todoList.toJSON()));
  } catch (error) {
    console.error('Error getting todoLists:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

export const getTodoListById = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const todoList = await TodoList.findByPk(id);
    if (todoList) {
      res.json(todoList.toJSON());
    } else {
      res.status(404).json({ error: 'TodoList not found' });
    }
  } catch (error) {
    console.error('Error getting todoList by ID:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

export const updateTodoList = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { title, desc } = req.body;
    const todoList = await TodoList.findByPk(id);
    if (todoList) {
      await todoList.update({ title, desc });
      res.json(todoList.toJSON());
    } else {
      res.status(404).json({ error: 'TodoList not found' });
    }
  } catch (error) {
    console.error('Error updating todoList:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

export const deleteTodoList = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const todoList = await TodoList.findByPk(id);
    if (todoList) {
      await todoList.destroy();
      res.json({ message: 'TodoList deleted successfully' });
    } else {
      res.status(404).json({ error: 'TodoList not found' });
    }
  } catch (error) {
    console.error('Error deleting todoList:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};